using FreeSql;
using KrasDD.Models;
using KrasDD.Services.Interfaces;

namespace KrasDD.Services.Implementations
{
    public class BaseService<T> : IBaseService<T>
        where T : class
    {
        protected readonly IFreeSql _freeSql;
        protected readonly IServiceProvider _serviceProvider;

        public BaseService(IFreeSql freeSql, IServiceProvider serviceProvider)
        {
            _freeSql = freeSql;
            _serviceProvider = serviceProvider;
        }

        public virtual async Task<T> GetByIdAsync(string id)
        {
            return await _freeSql
                .Select<T>()
                .Where(x => (x as AppBaseEntity).ID == id)
                .FirstAsync();
        }

        public virtual async Task<List<T>> GetAllAsync()
        {
            return await _freeSql.Select<T>().ToListAsync();
        }

        public virtual async Task<T> CreateAsync(T entity)
        {
            var result = await _freeSql.Insert(entity).ExecuteInsertedAsync();
            var createdEntity = result.FirstOrDefault();

            // 触发AddAfter事件
            if (createdEntity != null && createdEntity is AppBaseEntity appEntity)
            {
                var eventHandler = _serviceProvider.GetService<IEventHandler>();
                if (eventHandler != null)
                {
                    createdEntity = await eventHandler.HandleEventAsync("AddAfter", appEntity) as T;
                }
            }

            return createdEntity;
        }

        public virtual async Task<T> UpdateAsync(T entity)
        {
            var result = await _freeSql.Update<T>().SetSource(entity).ExecuteUpdatedAsync();
            var updatedEntity = result.FirstOrDefault();

            // 触发UpdateAfter事件
            if (updatedEntity != null && updatedEntity is AppBaseEntity appEntity)
            {
                var eventHandler = _serviceProvider.GetService<IEventHandler>();
                if (eventHandler != null)
                {
                    updatedEntity =
                        await eventHandler.HandleEventAsync("UpdateAfter", appEntity) as T;
                }
            }

            return updatedEntity;
        }

        public virtual async Task<bool> DeleteAsync(string id)
        {
            // 先获取要删除的实体用于触发事件
            T entityToDelete = null;
            if (typeof(T).IsSubclassOf(typeof(AppBaseEntity)))
            {
                entityToDelete = await GetByIdAsync(id);
            }

            var affected = await _freeSql
                .Delete<T>()
                .Where(x => (x as AppBaseEntity).ID == id)
                .ExecuteAffrowsAsync();

            // 触发DeleteAfter事件
            if (affected > 0 && entityToDelete != null && entityToDelete is AppBaseEntity appEntity)
            {
                var eventHandler = _serviceProvider.GetService<IEventHandler>();
                if (eventHandler != null)
                {
                    await eventHandler.HandleEventAsync("DeleteAfter", appEntity);
                }
            }

            return affected > 0;
        }
    }
}
